
import os
import sys

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# __file__===》当前文件名称，如dev.py
# os.path.abspath()==>绝对路径，如/home/python/Desktop/meiduo_sy22/meiduo_mall/meiduo_mall/settings/dev.py
# os.path.dirname()==>上层路径，如/home/python/Desktop/meiduo_sy22/meiduo_mall/meiduo_mall/settings
# os.path.dirname()==>上层路径，如/home/python/Desktop/meiduo_sy22/meiduo_mall/meiduo_mall
# BASE_DIR='/home/python/Desktop/meiduo_sy22/meiduo_mall/meiduo_mall'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 改写导包路径
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
# SECRET_KEY = '+oyb*yip$0vo_-a5%u)!$bj_#p5=2tp6l@e7v+1xf9kbf=c4!p'
SECRET_KEY = 'zlmzt_4*%(dp_b*381ll-7@5=cdlt%2aw!z583(cu9was60l09'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = [
    'www.meiduo.site',
    'www.fengliang.site',
    '127.0.0.1'

]

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 基于manage.py的路径
    # 'meiduo_mall.apps.users.apps.UsersConfig',
    # 简化路径===>meiduo_mall.apps.
    'users.apps.UsersConfig',
    'verifications.apps.VerificationsConfig',
    'contents.apps.ContentsConfig',
    'oauth.apps.OauthConfig',
    'areas.apps.AreasConfig',
    'goods.apps.GoodsConfig',
    'carts.apps.CartsConfig',
    'orders.apps.OrdersConfig',
    'payments.apps.PaymentsConfig',
    'haystack',#全文检索，根据分词查找数据
    'django_crontab',  # 定时任务
    #DRF框架
    'rest_framework',
    'book.apps.BookConfig',
    'books.apps.BooksConfig',
    'book_drf.apps.BookDrfConfig',
    'hero_drf.apps.HeroDrfConfig',
    'meiduo_admin.apps.MeiduoAdminConfig',
    # 'django_filters',

]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# 日志
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,  # 是否禁用已经存在的日志器
    'formatters': {  # 日志信息显示的格式
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
        },
    },
    'filters': {  # 对日志进行过滤
        'require_debug_true': {  # django在debug模式下才输出日志
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {  # 日志处理方法
        'console': {  # 向终端中输出日志
            'level': 'INFO',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {  # 向文件中输出日志
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(os.path.dirname(BASE_DIR), 'logs/meiduo.log'),  # 日志文件的位置
            'maxBytes': 300 * 1024 * 1024,
            'backupCount': 10,
            'formatter': 'verbose'
        },
    },
    'loggers': {  # 日志器
        'django': {  # 定义了一个名为django的日志器
            'handlers': ['console', 'file'],  # 可以同时向终端与文件中输出日志
            'propagate': True,  # 是否继续传递日志信息
            'level': 'INFO',  # 日志器接收的最低日志级别
        },
    }
}

# 指定用户模型类
AUTH_USER_MODEL = 'users.User'


ROOT_URLCONF = 'meiduo_mall.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',  # jinja2模板引擎
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            # 补充Jinja2模板引擎环境
            'environment': 'meiduo_mall.utils.jinja2_env.jinja2_environment',
        },
    },
]

WSGI_APPLICATION = 'meiduo_mall.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # 数据库引擎
        'HOST': '127.0.0.1',  # 数据库主机
        'PORT': 3306,  # 数据库端口
        'USER': 'feng',  # 数据库用户名
        'PASSWORD': '123456',  # 数据库用户密码
        'NAME': 'meiduo_feng'  # 数据库名字
    },
}

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
# 静态文件路径
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

# 缓存
CACHES = {
    "default": {  # 默认
        "BACKEND": "django_redis.cache.RedisCache",
        # 可修改：ip、端口、数据库编号
        "LOCATION": "redis://127.0.0.1:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "session": {  # session
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "verify_code": {  # 验证码
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },

    "history": { # 用户浏览记录
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/3",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },

    "carts": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/4",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
    }
},

}
# session
SESSION_ENGINE = "django.contrib.sessions.backends.cache"  # session的保存方式为缓存
SESSION_CACHE_ALIAS = "session"  # 缓存的键


#自定义认证类型,多账号登陆 当视图中调用authenticate 时，读取配置中重写父类的方法
AUTHENTICATION_BACKENDS = ['meiduo_mall.utils.auth_backends.MeiduoModelBackend']

#指定登录页视图页面
LOGIN_URL = '/login/'
 # QQ授权信息
QQ_CLIENT_ID = '101518219'#appid
QQ_CLIENT_SECRET = '418d84ebdc7241efb79536886ae95224'#appkey
QQ_REDIRECT_URI = 'http://www.meiduo.site:8000/oauth_callback'

# 邮件服务器配置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'  # 指定邮件后端
EMAIL_HOST = 'smtp.163.com'  # 发邮件主机
EMAIL_PORT = 25  # 发邮件端口
EMAIL_HOST_USER = 'fl15010152545@163.com'  # 授权的邮箱
EMAIL_HOST_PASSWORD = 'FL1994723fl'  # 邮箱授权时获得的密码，非注册登录密码
EMAIL_FROM = '美多商城<fl15010152545@163.com>'  # 发件人抬头
EMAIL_VERIFY_URL = 'http://www.meiduo.site:8000/emails/verification/'

# 访问fdfs文件的域名-----------------fdfs分布式文件系统,client客户端-调度工具track-storage硬盘搜寻数据
FDFS_URL = 'http://image.meiduo.site:8888/'
# 指定存储类型
DEFAULT_FILE_STORAGE = 'meiduo_mall.utils.storage.FdfsStorage'

#haystack的配置,建立搜索引擎的桥梁
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        'URL': 'http://192.168.166.21:9200/',  # Elasticsearch服务器ip地址，端口号固定为9200
        'INDEX_NAME': 'meiduo_feng',  # Elasticsearch建立的索引库的名称
    },
}
# 当添加、修改、删除数据时，自动生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
# haystack视图中规定每页显示几条数据
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 4

# 支付宝应用标识
ALIPAY_APPID = '2016092900625705'
# 如果使用沙箱则设置为True，如果正式环境则设置为False
ALIPAY_DEBUG = True
# 用户在支付宝支付成功后，支付宝会回到这个地址
ALIPAY_RETURN_URL = 'http://www.meiduo.site:8000/payment/status/'
# 支付宝网关
ALIPAY_GATEWAY = 'https://openapi.alipaydev.com/gateway.do?'

# https: // openapi.alipaydev.com / gateway.do

# 定时任务
CRONJOBS = [
    # 每1分钟生成一次首页静态文件
    ('*/1 * * * *', 'contents.crons.generate_static_index_html',
     '>> ' + os.path.join(os.path.dirname(BASE_DIR), 'logs/crontab.log')),
]
CRONTAB_COMMAND_PREFIX = 'LANG_ALL=zh_cn.UTF-8'  # 执行的方法中如果出现中文 ，必须指定这项配置

# #------------------
#
# # # DEF配置信息
# REST_FRAMEWORK = {
#     # 认证
#     'DEFAULT_AUTHENTICATION_CLASSES': (
#         'rest_framework.authentication.BasicAuthentication',   # 基本认证
#         'rest_framework.authentication.SessionAuthentication',  # session认证
#     ),
#     # 权限
#     'DEFAULT_PERMISSION_CLASSES': (
#         'rest_framework.permissions.IsAuthenticated',
#      ),
    # # 用户限流
    # 'DEFAULT_THROTTLE_CLASSES': (
    #     'rest_framework.throttling.AnonRateThrottle',
    #     'rest_framework.throttling.UserRateThrottle'
#     ),
#     # 类视图限流
#     'DEFAULT_THROTTLE_CLASSES': (
#         'rest_framework.throttling.ScopedRateThrottle',
#     ),
#     # 限流次数
#     'DEFAULT_THROTTLE_RATES': {
#         'generic': '3/day',
#         'viewset': '4/day'
#     },
#     # 过滤
#     'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
#     # 异常处理
#     'EXCEPTION_HANDLER': 'book_drf.utils.exception_handler'
#
# }